import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTop, WeaRightMenu, WeaNewScroll, WeaInput, WeaBrowser, WeaTextarea, WeaAlertPage, WeaTagGroup, WeaDialogFooter, WeaDatePicker, WeaCheckbox } from 'ecCom';
import { Row, Button, Col, Icon } from 'antd';
import { toJS } from 'mobx';
import AlertModal from '../public/AlertModal';
import SmsTempList from './SmsTemplate/TempList';
import moment from 'moment';

import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('sendSmsStore')
@inject('smsTempStore')
@observer
class EditSms extends React.Component {
	constructor(props) {
    	super(props);
	    this.state = {
			showAddBtn: true,
			tempText: '',
			showTemp: false,
			clickFlag: true,
			checked: false,
			isCus: props.isCus,
			sender: '',
		};
	}
	componentDidMount() {

	}
	componentWillReceiveProps(nextProps) {

	}
    render() {
		const { sendSmsStore } = this.props;
		if (sendSmsStore.hasRight === '1') {
			if (this.state.isCus) {
				return (
					<div className="sms-editSms" style={{ height: '100%' }} onClick={this.pageClick.bind(this)}>
						<SmsTempList ecId={`${this && this.props && this.props.ecId || ''}_SmsTempList@8fc69u`}
  visible={sendSmsStore.showFlag}
  doRefresh={this.doRefresh}
  doClose={() => {
								sendSmsStore.closeTempList();
							}}
						/>
					 	<div className="dialog-content">
						<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@sywicy`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
							{this.getEditSms() }

						</WeaRightMenu>

						<WeaDialogFooter ecId={`${this && this.props && this.props.ecId || ''}_WeaDialogFooter@cndokr`} buttons={this.getTopButtons('WeaDialogFooter')} moreBtn={this.getMoreBtn()} />
						</div>
					</div>

				);
			}
				return (
					<div className="sms-editSms" style={{ height: '100%' }} onClick={this.pageClick.bind(this)}>
						<SmsTempList ecId={`${this && this.props && this.props.ecId || ''}_SmsTempList@be07o7`}
  visible={sendSmsStore.showFlag}
  doRefresh={this.doRefresh}
  doClose={() => {
								sendSmsStore.closeTempList();
							}}
						/>
						<WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jcoigi`}
  title={getLabel(16635, '发送短信')}
  loading={false}
  icon={<i className="icon-coms-message" />}
  iconBgcolor="#0079de"
  buttons={this.getTopButtons('WeaTop')}
  showDropIcon={true}
  dropMenuDatas={this.getRightMenu()}
  onDropMenuClick={this.onRightMenuClick.bind(this)}
						>
							<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@sh8wg5`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
							{this.getEditSms() }
							</WeaRightMenu>
						</WeaTop>
					</div>
				);
		} else if (sendSmsStore.hasRight === '0') {
			return (
				<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@1k4tb3`} top={'36%'}>
					<div>
                        {getLabel(2012, '对不起，您暂时没有权限！')}
					</div>
				</WeaAlertPage>
			);
		}
			return (
				<div />
			);
	}
	validate(v) { // 验证通过返回false 不通过返回true
	//	var regex = /^((\+)?86|((\+)?86)?)0?1[34578]\d{9}$/;
		let regex = /^[\d-\+]*$/;
		let ret = !regex.test(v);
		return ret;
	}
	getEditSms() {
		const { sendSmsStore } = this.props;
		const { checked } = this.state;
		let hrmIdsBrowserParam = {
			hasAddBtn: false,
			hasAdvanceSerach: true,
			isAutoComplete: 1,
			isDetail: 0,
			isMultCheckbox: false,
			isSingle: false,
			linkUrl: '/hrm/resource/HrmResource.jsp?id=',
			quickSearchName: '',
			title: getLabel(839, '多人力资源'),
			type: '17',
			viewAttr: 2,
		};

		let crmIdsBrowserParam = {
			hasAddBtn: false,
			hasAdvanceSerach: true,
			isAutoComplete: 1,
			isDetail: 0,
			isMultCheckbox: false,
			isSingle: false,
			linkUrl: '/spa/crm/static/index.html#/main/crm/contacterView?contacterId=',
			quickSearchName: '',
			title: getLabel(17129, '客户联系人'),
			type: '67',
			viewAttr: 2,
		};

		let offset = 4;
		let titlecol = 4;
		let fieldcol = 10;
		let marginBottomValue = 16;
		if (this.state.isCus) {
			offset = 2;
			titlecol = 5;
			fieldcol = 11;
		}
		const contentStyle = {
			display: this.state.showTemp ? 'block' : 'none',
		};
		if (sendSmsStore.sendCrm) {
			crmIdsBrowserParam = { ...crmIdsBrowserParam, ...{ replaceDatas: toJS(sendSmsStore.sendCrm) } };
		}

		if (!this.state.showAddBtn) contentStyle['border-bottom'] = 0;
		return (
				<div style={{ height: '100%' }} className="">
					<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@btwmkq`} className="" style={{ marginBottom: `${marginBottomValue}px`, paddingTop: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@58z3ag`} offset={offset} span={titlecol} style={{ paddingLeft: '40px' }}>
							<span>{getLabel(32926, '短信接收员工')}: </span>
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ovsyrv`} span={fieldcol} style={{ marginLeft: '43px' }}>
							<WeaTagGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaTagGroup@f67flr`} ref="number_field" splitChar="," noDefault={true} validate={this.validate.bind(this)} datas={toJS(sendSmsStore.sendHrm)} />
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2fb26d`} span={1} style={{ marginLeft: '3px', paddingTop: '6px' }}>
							<span className="icon-coms-Explain tip-input" style={{ fontSize: '15px' }} title={getLabel(384205, '自定义号码可直接输入,按回车进行确认')} />
						</Col>
					</Row>
					{!sendSmsStore.isGov && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@w6hqbp`} className="" style={{ marginBottom: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@uhizbl`} offset={offset} span={titlecol} style={{ paddingLeft: '40px' }}>
							<span>{getLabel(32928, '短信接收客户联系人')}: </span>
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@5s4o8u`} span={fieldcol} style={{ marginLeft: '43px' }}>
							<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@5ql658`}
  {...crmIdsBrowserParam}
  onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, 'crmIds')}
							/>
						</Col>
					</Row>
					}

					<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@f7yhng`} className="" style={{ marginBottom: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jehsrp`} offset={offset} span={titlecol} style={{ paddingLeft: '40px', lineHeight: '32px' }}>
							<span >{getLabel(18529, '短信内容')}: </span>
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tnnova`} span={fieldcol} style={{ marginLeft: '43px' }}>
							<div className="msg-tool"><div style={{ marginTop: '5px', display: 'inline-block' }}>{getLabel(20074, '你已输入')} {sendSmsStore.msgCount || 0} {getLabel(20075, '个字符')}</div>
								<div style={{ float: 'right', marginTop: '5px', marginRight: '20px', display: 'inline-block' }}>
									<div style={{ display: 'inline-block' }}>
										<div className="temp-btn" onClick={this.showTemp}>
											{getLabel(28049, '短信模板')}
										</div>
										<div className="temp-content" style={contentStyle}>
											<div className="arrow1" />
											<div className="arrow2" />
											<div className="temp-list">
												{sendSmsStore.groups.length > 0 &&
													<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@qv47u9`} height={120}>
														<ul>
															{
																sendSmsStore.groups.map(item => (<li onClick={this.checkTemp.bind(this, item)}>
																		<span>{item.title}</span>
																	</li>))
															}
														</ul>
													</WeaNewScroll>
												}
											</div>

											<div className="temp-foot-btn" title={getLabel(611, '添加')} onClick={this.doAdd} >
												<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@b3n1sj`} type="plus-circle-o" />
											</div>

										</div>
									</div>
									<div className="icon-coms-currency setting-btn" title={getLabel(518871, '短信模板维护')} onClick={this.openTempList} />
								</div>
							</div>
							<WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@pm7a2c`} viewAttr={3} ref="textArea" minRows={8} value={sendSmsStore.msg || ''} onChange={value => this.onChange(value, 'msg')} />
						</Col>
					</Row>
					{sendSmsStore.showCusSign && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@j890rq`} className="" style={{ marginBottom: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4amxv2`} offset={offset} span={titlecol} style={{ paddingLeft: '40px' }}>
							<span>{getLabel(21800, '落款')}: </span>
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@pkmjj7`} span={fieldcol} style={{ marginLeft: '43px' }}>
						<WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@dgry7a`}
  id="test"
  value={checked}
  onChange={(value) => {
								this.setState({ checked: value });
							}}
						/>
						{}
						<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@4xmge7`}
  ref="sender"
  viewAttr={3}
  value={this.state.sender}
  onChange={value => this.onChange(value, 'sender')}
						/>
						</Col>
					</Row>
					}
					{sendSmsStore.showReply &&
						<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2j929s`} className="tip-msg" style={{ marginBottom: '10px' }}>
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@i5qo2v`} offset={offset} span={titlecol} style={{ paddingLeft: '40px', lineHeight: '32px' }} />
							<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@br3ymk`} span={fieldcol} style={{ marginLeft: '43px' }}>
								<div style={{ display: 'flex', display: '-webkit-flex' }}>
									<span style={{ width: '100%' }}>{getLabel(384501, '回复方法：回复 ID+R+回复内容 （ID从收到的短信中可以获得')}</span><br />
								</div>
								<div style={{ display: 'flex', display: '-webkit-flex' }}>
									<span style={{ width: '10%' }}>{getLabel(520525, '例如：')} </span><br />
									<span style={{ width: '90%' }}> {getLabel(520523, '收到短信为：收到的消息内容(86)')} </span><br />
								</div>
								<div style={{ display: 'flex', display: '-webkit-flex' }}>
									<span style={{ width: '10%' }} />
									<span style={{ width: '90%' }}> {getLabel(520524, '回复应该为：86R 发送的消息内容')}</span>
								</div>
							</Col>
						</Row>}
					<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ointwq`} className="" style={{ marginBottom: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zw9mcg`} offset={offset} span={titlecol} style={{ paddingLeft: '40px', lineHeight: '32px' }}>
							<span >{getLabel(32028, '定时发送')}: </span>
						</Col>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tkrub8`} span={fieldcol} style={{ marginLeft: '43px' }}>
							<div className={'regularChk'}>
								<WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@v12qum`}
  id={'regularChk'}
  display={'switch'}
  value={sendSmsStore.regularChk}
  onChange={(value) => {
										this.onChange(value, 'regularChk');
										sendSmsStore.setRegularDateTime(moment().format('YYYY-MM-DD HH:mm'));
									}}
								/>
								{sendSmsStore.regularChk == 1 && <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@iek76z`}
  viewAttr={3}
  showTime={{ format: 'HH:mm' }}
  format="yyyy-MM-dd HH:mm"
  value={sendSmsStore.regularDateTime}
  onChange={value => this.onChange(value, 'regularDateTime')}
								/>}
							</div>
						</Col>
					</Row>
				</div>
		);
	}

	getTopButtons(arg) {
		const { loading } = this.props.sendSmsStore;
		let btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4and3s@${arg}`} type="primary" disabled={loading} onClick={() => { this.onRightMenuClick(0); }}>{getLabel(2083, '发送')}</Button>];
		return btns;
}

 	getRightMenu() {
        let btns = [];
        btns.push({
			key: '0',
            icon: <i className="icon-coms-Approval" />,
			content: getLabel(2083, '发送'),
        });
        return btns;
	}

	getMoreBtn() {
        let btns = [];
        btns.push({
			key: '0',
            icon: <i className="icon-coms-Approval" />,
			content: getLabel(2083, '发送'),
			onClick: () => { this.onRightMenuClick(0); },
        });
        return { datas: btns };
	}

    // 右键菜单事件绑定
    onRightMenuClick(key) {
			const { setLoading, regularChk, regularDateTime } = this.props.sendSmsStore;
		const { sender } = this.state;
        if (key == '0') {
			let numberValueObj = this.refs.number_field.valueMap;
			let hrmid = [];
			let cusNo = [];
			for (let index in numberValueObj) {
				if (numberValueObj[index].type) {
					hrmid.push(numberValueObj[index].id);
				} else {
					cusNo.push(numberValueObj[index].id);
				}
			}
			const { sendSmsStore } = this.props;
			let sta = { sender, msg: sendSmsStore.msg, crmIds: sendSmsStore.crmIds, requestid: sendSmsStore.requestid };
			let param = { ...sta, cusNumber: cusNo.toString(), hrmIds: hrmid.toString(), regularChk, regularDateTime };
			if (hrmid.length == 0 && cusNo.length == 0 && sendSmsStore.crmIds.length == 0) {
				AlertModal(getLabel(84463, '接收人不能为空！'));
				return;
			}

        	if (!sendSmsStore.msg) {
				AlertModal(getLabel(384506, '短信内容不能为空！'));
				return;
			}
			if (sendSmsStore.showCusSign && !sender) {
				AlertModal(getLabel(21801, '落款不能为空！'));
				return;
			}
			if (regularChk == 1 && !regularDateTime) {
				AlertModal(getLabel(506448, '定时发送时间不能为空'));
				return;
			}
			setLoading(true);

			let ret = sendSmsStore.send(param);
			Promise.all([ret]).then((result) => {
				this.getResult(result[0].successflag);
				setLoading(false);
			});
        }
    }
	onChange=(values, type) => {
		const { sendSmsStore } = this.props;
	    if (type == 'msg') {
			sendSmsStore.setMsg(values);
	    } else if (type == 'regularChk') {
			sendSmsStore.setRegularChk(values);
		} else if (type == 'regularDateTime') {
			sendSmsStore.setRegularDateTime(values);
		} else {
			this.setState({ [type]: values });
		}
	}

    onChangeBrowser=(ids, names, datas, type) => {
		const { sendSmsStore } = this.props;
		sendSmsStore.setCrm(ids, datas);
	}

	getResult =(result) => {
		this.props.changeType(result);
	}

	checkTemp =(item) => {
		const { sendSmsStore } = this.props;
		this.refs.textArea.setValue(item.content);
	}

	doAdd = (e) => {
		const { smsTempStore: { showTempDataAndMsg, setDataId } } = this.props;
		setDataId('');
		showTempDataAndMsg();
		e.stopPropagation();
	}

	openTempList = () => {
		const { sendSmsStore, smsTempStore } = this.props;
		smsTempStore.doLoading();
		sendSmsStore.openTempList();
	}

	showTemp=() => {
		this.setState({ showAddBtn: true });
		if (this.state.showTemp) {
			this.setState({ showTemp: false });
		} else {
			this.setState({ showTemp: true });
		}
	}
	saveTemp = () => {
		let value = this.state.tempText;
		const { sendSmsStore } = this.props;
		sendSmsStore.quickSaveTemp({ tempText: value });
		this.setState({ showAddBtn: true });
	}

	pageClick=() => {
		if (this.state.clickFlag) {
			if (this.state.showTemp) {
				this.setState({ showTemp: false });
			}
		}
		this.setState({ clickFlag: true });
	}

	tempClick=(e) => {
		e.stopPropagation();
	}

	doRefresh=() => {
		const { sendSmsStore } = this.props;
		sendSmsStore.getOptions();
	}
}

export default EditSms;
